#!/usr/bin/env node

// import puppeteer from "puppeteer-core";
import puppeteer from "puppeteer";
import chalk from "chalk";
import wifi from "node-wifi";
import config from './config.js'
// console.log('config: ', config);

// 代理登录
const proxyLogin = async () => {
  const browser = await puppeteer.launch({
    // 此处可以使用 false 有头模式进行调试, 调试完注释即可
    // headless: false,
    // executablePath: "C:/Program Files/Google/Chrome/Application/chrome.exe",
    // executablePath: ''
  });
  const page = await browser.newPage();

  try {
    await page.goto(config.webLoginAddress);
    // 输入账号密码，可根据实际情况修改
    await page.type("#PtUser", config.user);
    await page.type("#PtPwd", config.password);

    // 点击登录
    await page.click(".login-btn");

    console.log("登录中...");

    // 判断是否登录成功
    await page.waitForSelector("input[value='下线']");
    console.log(chalk.white.bgGreen.bold("登录成功！！！"));
    await browser.close();
  } catch (error) {
    console.log("error: ", error);
    console.log(chalk.red.bgWhite.bold("请检查win无线网是否已连接"));
  }
};

const connectWifi = () => {
  wifi.connect({
    ssid: config.wifiName,
    password: ""
  }, () => {
    console.log("Connected");

    // 网页登录
    proxyLogin();
  });
}

const server = async () => {
  wifi.init({
    iface: null, // network interface, choose a random wifi interface if set to null
  });

  // 获取当前网络信息
  wifi.getCurrentConnections((err, data) => {
    if (err) {
      console.log(err);
      return;
    }

    console.log('data', data);

    // 判断是否已链接
    if (data.length === 1) {
      console.log('已连接wifi');
      wifi.disconnect().then(() => {
        connectWifi()
      })
    } else {
      connectWifi()
    }
  });
};

server();